package web.rssReader;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import data.Episode;
import data.Show;

/**
 * RssReader
 * 
 * Template found @ http://javamix.wordpress.com/2009/06/04/read-rss-feeds-by-using-java/
 * @author katta vijay
 * @modifier Bionic Weasel
 */
public class DailyTvTorrentRssReader extends RssReaderInterface
{

	public DailyTvTorrentRssReader(String showName)
	{
		this.stringURL = "http://www.dailytvtorrents.org/rss/show/"+
		showName.replace(' ', '-').toLowerCase();
		
		this.showName = showName;
		this.connect();
	}
	/**
	 * Gets the shows from the RSS Feed and returns them in a LinkedList<Show>
	 * @return Shows in a LinkedList.
	 */
	public Show getShow()
	{
		if(this.url == null)
		{
			System.err.println("this.url is not declared!");
		}
		
		Show show = new Show(showName);
		
		try 
		{	
			DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
			
			Document doc = builder.parse(this.url.openStream());
			
			NodeList nodes = doc.getElementsByTagName("item");
	
			for(int i=0;i<nodes.getLength();i++) 	
			{
				Element element = (Element)nodes.item(i);
				String showName = null;
				String epTitle = null;
				int epNum = 0;
				int seasonNum = 0;
				String link;
				String pubDate;
				
				String[] tempString = new String[VALUE];
				String[][] description = new String[VALUE][2];
				
				
				tempString= this.getElementValue(element,"guid").split("_");
				
				int epNumIndex = tempString[1].indexOf('E')+1;
				int sNumIndex = tempString[1].indexOf('S')+1;
				epNum =Integer.parseInt(tempString[1].substring(epNumIndex, tempString[1].length()));
				String seasonNumString = tempString[1].substring(sNumIndex, epNumIndex-1);
				seasonNum = Integer.parseInt(seasonNumString);
				link = this.getAttributeValue(element, "enclosure","url");
				
				//pubdate has a format like:  "Sat, 21 May 2011 00:40:04 -0500"
				pubDate = getElementValue(element,"pubDate");
				
				SimpleDateFormat dateFormat = new SimpleDateFormat( "dd MMM yyyy hh:mm:ss Z" );
				pubDate = pubDate.substring(5);
				Date date = new Date();
				try {
					date = dateFormat.parse( pubDate );
				} catch (ParseException e) {
					System.out.println("Date-parse fail for EztvRssReader");
				}
				Episode ep = new Episode(epNum, epTitle, link, "", date);
			
				show.addEpisode(ep, seasonNum);
			}
			
		}
		catch(Exception ex) 
		{
			System.err.println(ex.getLocalizedMessage());
		}
		return show;
	}
}